package com.shwread.android.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.UpdateApkService;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.page.MainTabPage;

import java.io.File;

import logic.bean.AppInfo;
import logic.constants.AppConfig;
import logic.constants.DefaultConsts;
import logic.util.SDcardUtil;
import logic.util.ScreenUtil;
import logic.util.Util;


public class VersionDialog
        extends
        Dialog
{
	
	public static long               downloadId;
	
	private AppInfo                  appInfo;
	private Context                  context;
	
	private TextView                 tvVersion;
	private TextView                 tvSize;
	private TextView                 tvDate;
	private TextView                 tvContent;
	private LinearLayout                   vOk;
	private View                     vDivider;
	private LinearLayout                     vCancel;
	private String                   localPath    = Environment.getExternalStorageDirectory().getPath() + "/" + DefaultConsts.homeFilePath + "/";
	private String                   filePath     = "";
	private Boolean                  manualUpdate = false;
	private TextView isVersion;
	
	private ForceUpdateClickListener listener;
	
	private boolean                  is_existed;
	private MainTabPage mainPage;
	public void setPage(MainTabPage page){
		this.mainPage = page;
	}
	
	public VersionDialog(Context context) {
		super(context, R.style.common_dialog);
		
		
		this.context = context;
		
		findViews();
		setListeners();
	}
	
	public void setVersionInfo(AppInfo appInfo) {
		this.appInfo = appInfo;
		tvVersion.setText(appInfo.versionCode);
		tvSize.setText(appInfo.sizeInfo + "M");
		tvContent.setText(appInfo.descInfo);
		
		filePath = localPath + getApkName(String.valueOf(appInfo.versionCode2));
		
		is_existed = checkFileIsExisted(filePath);
		
//		if (is_existed)
//		{
//			isVersion.setText("安装");
//		}
		
		if (appInfo.isForce())
		{
			setCanceledOnTouchOutside(false);
			
//			vDivider.setVisibility(View.GONE);
			vCancel.setVisibility(View.GONE);
//			if (is_existed)
//			{
//				isVersion.setText("安装");
//			}
//			else
			isVersion.setText("升级");
		}
		else
		{
			
//			if (is_existed)
//			{
//				isVersion.setText("安装");
////				vDivider.setVisibility(View.GONE);
//				vCancel.setVisibility(View.VISIBLE);
//			}
//			else
//			{
				setCanceledOnTouchOutside(true);
//				vDivider.setVisibility(View.VISIBLE);
				vCancel.setVisibility(View.VISIBLE);
//			}
		}
	}
	
	private void findViews() {
		View v = LayoutInflater.from(context).inflate(R.layout.new_version_dialog, null);
		isVersion=(TextView)v.findViewById(R.id.isVersion);
		
		tvVersion = (TextView) v.findViewById(R.id.version_dialog_version);
		tvSize = (TextView) v.findViewById(R.id.version_dialog_size);
//		tvDate = (TextView) v.findViewById(R.id.version_dialog_date);
		tvContent = (TextView) v.findViewById(R.id.version_dialog_content);
		vOk = (LinearLayout) v.findViewById(R.id.version_dialog_ok);
//		vDivider = v.findViewById(R.id.version_dialog_divider);
		vCancel = (LinearLayout)v.findViewById(R.id.version_dialog_cancel);
		
		setContentView(v);
		getWindow().setLayout(ScreenUtil.dip2px(245), ScreenUtil.dip2px(324));
	}
	
	private void setListeners() {
		ClickListener l = new ClickListener();
		
		vOk.setOnClickListener(l);
		vCancel.setOnClickListener(l);
	}
	
	public void setManualUpdate() {
		this.manualUpdate = true;
	}
	
	public void clickOk() {
		this.dismiss();
		
		if (appInfo.isForce() && !manualUpdate)
		{
			ForceUpdate();
		}
		else
		{
//			if (is_existed)
//			{
//				setupApp(getContext(), filePath);
//			}
//			else
//			{
				if (appInfo.fileUrl != null)
				{
					UpdateApkService.setURL(appInfo, filePath);
					Intent intent = new Intent(context, UpdateApkService.class);
					context.startService(intent);
				}
//			}
		}
		//		VersionInfo [descInfo=修复bug, fileUrl=http://121.41.18.34:8094/zqswManager/apk/ZQSW_tyyd_android_1.1.0.apk, isForce=true, isReleased=true, sizeInfo=5.55, sysType=2, versionCode=1.1.0, versionCode2=1004]
	}
	
	boolean checkFileIsExisted(String filePath) {
		boolean isExisted = false;
		File fileDir = new File(localPath);
		if (!fileDir.exists())
		{
			fileDir.mkdir();
		}
		File file = new File(filePath);
		if (file.exists())
		{
			if (file.getName().equals(getApkName(appInfo.versionCode2 + "")))
			{
				isExisted = true;
			}
			else
			{
				file.delete();
				isExisted = false;
			}
		}
		else
		{
			isExisted = false;
		}
		return isExisted;
	}
	
	void clickCancel() {
		dismiss();
	}
	
	@Override
	public void cancel() {
		super.cancel();
	}
	
	@Override
	public void show() {
		//		if (versionInfo.isForce)
		//		{
		//			ForceUpdate();
		//		}
		super.show();
	}
	
	private void ForceUpdate() {
		if (is_existed)
		{
			setupApp(getContext(), filePath);
		}
		else
		{
			if (appInfo.fileUrl != null)
			{
				dismiss();
				if (listener != null)
				{
					listener.ForceUpdateClick(filePath);
				}
				else
				{
					Toast.makeText(getContext(), "没有点击事件", Toast.LENGTH_SHORT).show();
				}
			}
		}
	}
	
	private class ClickListener
	        implements
	        View.OnClickListener
	{
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.version_dialog_ok:
					clickOk();
					break;
				case R.id.version_dialog_cancel:
					clickCancel();
					break;
			}
		}
		
	}
	
	private String getApkName(String version) {
		return AppConfig.getChannelName() + version + ".apk";
	}
	
	private boolean checkLockInstallFile(String fileName) {
		File file = new File(SDcardUtil.getHomePath() + fileName);
		if (null != file && file.exists())
		{
			setupApp(context, SDcardUtil.getHomePath() + fileName);
			return true;
		}
		else
		{
			
			return false;
		}
	}
	
	public void SetForceUpdateClick(ForceUpdateClickListener listener) {
		
		this.listener = listener;
	}
	
	public interface ForceUpdateClickListener
	{
		void ForceUpdateClick(String FilePath);
	}
	
	void setupApp(Context context, String filePath) {
		if (context != null && Util.isNotEmpty(filePath))
		{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
			context.startActivity(intent);
			if(mainPage != null) mainPage.exit();
		}
		
	}
}
